package com.example.demo.controller;

import com.example.demo.dto.ApiResponse;
import com.example.demo.dto.UpdateRequest;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.example.demo.entity.User;
import com.example.demo.dto.passwoedRequest;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
public class userController {
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final UserRepository userRepository;

    public userController(UserService userService, PasswordEncoder passwordEncoder, UserRepository userRepository) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
        this.userRepository = userRepository;
    }

    @PutMapping("/RevisePassword/{id}")
    public ApiResponse<String> revisePassword(
            @RequestBody passwoedRequest result,
            @PathVariable long id,
            Authentication authentication) {
        try {
            String username = authentication.getName();

            User user = userRepository.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("用户不存在"));

            if (!passwordEncoder.matches(result.old_password(), user.getPassword())) {
                return ApiResponse.error(402, "原密码错误");
            }

            if (!user.getUsername().equals(username) && !userService.authPress(username).equals("e56e1e0d96783898")) {
                return ApiResponse.error(403, "无权修改此用户密码");
            }

            if (result.password() == null || result.password().length() < 6 || result.password().trim().isEmpty()) {
                return ApiResponse.error(400, "密码格式错误");
            }
            String encodedPassword = passwordEncoder.encode(result.password());

            user.setPassword(encodedPassword);
            userRepository.save(user);
            return ApiResponse.success("密码修改成功");
        } catch (Exception e) {
            return ApiResponse.error(400, "密码修改失败");
        }
    }

    @PostMapping("/ResetPassword/{id}")
    public ApiResponse<String> resetPassword(@PathVariable long id, Authentication authentication) {
        try {
            String username = authentication.getName();

            User user = userRepository.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("用户不存在"));

            if (!user.getUsername().equals(username) && !userService.authPress(username).equals("e56e1e0d96783898")) {
                return ApiResponse.error(403, "无权重置此用户密码");
            }


            String encodedPassword = passwordEncoder.encode("Rec123456");

            user.setPassword(encodedPassword);
            userRepository.save(user);
            return ApiResponse.success("密码重置成功");
        } catch (Exception e) {
            return ApiResponse.error(400, "密码重置失败");
        }
    }

    @DeleteMapping("/Delete/{id}")
    public ApiResponse<String> delete(
            @PathVariable long id,
            Authentication authentication) {
        String username = authentication.getName();
        User user = userRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));

        if (userService.authPress(username).equals("e56e1e0d96783898") && username.equals(user.getUsername())) {
            return ApiResponse.error(401, "管理员不能自己删除自己");
        }

        if (!userService.authPress(username).equals("e56e1e0d96783898")) {
            return ApiResponse.error(403, "无权删除此用户");
        }
        try {
            userRepository.delete(user);
            return ApiResponse.success("用户删除成功");
        } catch (Exception e) {
            return ApiResponse.error(400, "用户删除失败");
        }
    }

    @PostMapping("/List")
    public ApiResponse<List<Map<String, Object>>> list() {
        try {
            List<Map<String, Object>> PageList = userRepository.findAll().stream()
                    .map(user -> {
                        Map<String, Object> map = new LinkedHashMap<>();
                        map.put("id", user.getId());
                        map.put("username", user.getUsername());
                        map.put("name", user.getName());
                        String authText = switch(user.getAuth()) {
                            case "e56e1e0d96783898" -> "管理员";
                            case "02229d89cc94d086" -> "普通用户";
                            default -> "未知角色";
                        };
                        map.put("auth", authText);
                        map.put("status", user.getStatus());
                        map.put("registerTime", user.getRegisterTime());
                        return map;
                    })
                    .collect(Collectors.toList());
            return ApiResponse.success(200, "获取成功", PageList);
        } catch (Exception e) {
            return ApiResponse.error(400, "获取失败");
        }
    }

    @PutMapping("/ResetName/{id}")
    public ApiResponse<Map<String, String>> resetName(
            @RequestParam String nickname,
            Authentication authentication,
            @PathVariable long id) {
        try {
            String username = authentication.getName();
            User user = userRepository.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
            if (!user.getUsername().equals(username) && !userService.authPress(username).equals("e56e1e0d96783898")) {
                return ApiResponse.error(403, "无权更改此用户昵称");
            }

            if (nickname == null || nickname.isEmpty()) {
                return ApiResponse.error(401, "昵称不能为空");
            }
            user.setName(nickname);
            userRepository.save(user);
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("nickname", nickname);
            tokenMap.put("username", username);
            return ApiResponse.success(200, "昵称更改成功", tokenMap);
        } catch (Exception e) {
            return ApiResponse.error(400, "昵称更改失败");
        }
    }

    /*
    * /UpdateAuth/{id}/{Auth}
    * {id}: 用户id
    * {Auth}: 1普通用户，2管理员用户
    * return json
    * */
    @PutMapping("/UpdateAuth/{id}/{Auth}")
    public ApiResponse<String> updateAuth(Authentication authentication, @PathVariable long id, @PathVariable long Auth) {
        try {
            String username = authentication.getName();
            User user = userRepository.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
            if (!userService.authPress(username).equals("e56e1e0d96783898")) {
                return ApiResponse.error(403, "无权更改此用户权限");
            }

            String auth = "";

            if (Auth == 1) {
                auth = "02229d89cc94d086";
            } else if (Auth == 2) {
                auth = "e56e1e0d96783898";
            }
            user.setAuth(auth);
            userRepository.save(user);
            return ApiResponse.success("修改权限成功");
        } catch (Exception e) {
            return ApiResponse.error(400, "权限修改失败");
        }
    }

    @PostMapping("/userInfo/{id}")
    public ApiResponse<List<Map<String, Object>>> getUser(@PathVariable Long id) {
        try {
            User user = userRepository.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
            List<Map<String, Object>> userInfo = userRepository.findById(id).stream()
                    .map(user1 -> {
                        Map<String, Object> map = new LinkedHashMap<>();
                        map.put("id", user1.getId());
                        map.put("username", user1.getUsername());
                        map.put("name", user1.getName());
                        String authText = switch(user1.getAuth()) {
                            case "e56e1e0d96783898" -> "管理员";
                            case "02229d89cc94d086" -> "普通用户";
                            default -> "未知角色";
                        };
                        map.put("auth", authText);
                        map.put("registerTime", user1.getRegisterTime());
                        map.put("status", user1.getStatus());
                        return map;
                    })
                    .collect(Collectors.toList());
            return ApiResponse.success(200, "请求成功", userInfo);
        } catch (Exception e) {
            return ApiResponse.error(401, "用户不存在");
        }
    }

    @PutMapping("/Update/{id}")
    public ApiResponse<String> update(@PathVariable Long id, @RequestBody UpdateRequest body, Authentication authentication) {
        try {

            String username = authentication.getName();

            User user = userRepository.findById(id)
                    .orElseThrow(() -> new IllegalArgumentException("用户不存在"));

            if (!userService.authPress(username).equals("e56e1e0d96783898")) {
                return ApiResponse.error(403, "无权修改此用户");
            }

            user.setAuth(body.role());
            user.setUsername(body.username());
            user.setStatus(body.status());
            user.setName(body.nickname());
            userRepository.save(user);
            return ApiResponse.success("更新成功");
        } catch (Exception e) {
            return ApiResponse.error(401, "更新用户信息失败");
        }
    }

    @PostMapping("/verify")
    public ApiResponse<String> verify() {
        return ApiResponse.success("验证成功");
    }
}